-module(login).
-export([login/1]).
-include("records.hrl").
-import(cookie, [check_cookie/1]).
-import(db_user, [get_user/1, update_user_last_login/1]).


% Manage the login action
login(A) ->
	case check_cookie(A) of
		% If the user is not already logged in
		{error, _} ->
			% Parse the request and obtain the values entered by the user
			L = yaws_api:parse_post(A),
			Name = utils:value_from_key("username", L),
			Pwd = utils:value_from_key("password", L),
			
			case Name =:= error of
				% If the user entered values
				false ->
					N = list_to_atom(Name),
					P = list_to_atom(Pwd),
					
					% Check if the user exists
					case get_user(N) of
					
						% If it exists, obtain data related to the homework, create the cookie and store it
						{atomic, [{user, _, N, P, _, SSp, SSw, LSp, LSw, HG, HD, RatingH, Up, Times, RatingA, Level}]} ->
							{atomic, HomeworkToDo} = db_homework_to_do:get(N),
							{atomic, HomeworkToCorrect} = db_homework_to_correct:get(N),
							{atomic, HomeworkToRate} = db_homework_to_rate:get(N),
							
							S = #session{user = N,
											speak_spanish = SSp,
											speak_swedish = SSw,
											learn_spanish = LSp,
											learn_swedish = LSw,
											homework_given = HG,
											homework_done = HD,
											homework_to_do = length(HomeworkToDo),
											homework_to_correct = length(HomeworkToCorrect),
											homework_to_rate = length(HomeworkToRate),
											rating_homework = RatingH,
											uploaded_audios = Up,
											times_listened = Times,
											rating_audio = RatingA,
											level = Level},
							Cookie = yaws_api:new_cookie_session(S),
							
							% Update the users table with
							db_user:update_user_last_login(N),
							
							% Redirect depending on from where the user has arrived to the login page
							case utils:value_from_key("url", L) of
								"nourl" ->
									{redirect, main, Cookie};
								Url ->
									{redirect, Url, Cookie}
							end;
							
						% If it doesn't exist, badlogin is returned
						{atomic, _} ->
							badlogin
					end;
					
				% If the user has not entered password or name, redirect to index page
				true ->
					{redirect, index}
			end;
		% If the user is already logged in, it orders to redirect to the main page
		{ok, _, _} ->
			{redirect, main}
	end.
